package com.le.tester.webpage.redis.controller;

import com.le.tester.common.ServerResponse;
import com.le.tester.common.enums.ResponseCode;
import com.le.tester.delay.DelayedOrder;
import com.le.tester.webpage.redis.service.RedisOrderAutoConfirmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 描述：redis实现七天自动收货，20分钟自动关闭订单
 */
@Controller
@RequestMapping("/order/")
@Api(tags = {"redis订单自动处理业务模块"})
public class RedisOrderAutoConfirmController {

    private static final Logger LOG = LoggerFactory.getLogger(RedisOrderAutoConfirmController.class);

    @Autowired
    private RedisOrderAutoConfirmService orderAutoConfirmService;

    /**
     * 创建订单
     *
     * @param orderId：订单id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ApiOperation(value = "创建订单", notes = "订单号选传")
    public ServerResponse<String> createOrder(@RequestParam(value = "orderId", required = false) String orderId) {
        //测试使用
        long currentTime = System.currentTimeMillis();
        orderId = String.valueOf(currentTime + new Random().nextInt(100));
        LOG.info("生成的订单号:{}", orderId);
        //检验参数
        if (StringUtils.isBlank(orderId)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        try {
            DelayedOrder delayOrder = orderAutoConfirmService.createOrder(orderId);
            return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(), delayOrder.getValue());
        } catch (Exception e) {
            LOG.info("创建订单异常：{}", e.getMessage());
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
        }
    }

    @ResponseBody
    @RequestMapping(value = "pay", method = RequestMethod.POST)
    @ApiOperation(value = "支付订单", notes = "订单号码必填")
    public ServerResponse payOrder(@RequestParam("orderId") String orderId) {
        //检验参数
        if (StringUtils.isBlank(orderId)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        try {
            orderAutoConfirmService.payOrder(orderId);
            return ServerResponse.createBySuccess();
        } catch (Exception e) {
            LOG.info("支付异常：{}", e.getMessage());
            return ServerResponse.createByError();

        }

    }

}
